package com.ray.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.xmlbeans.impl.xb.xsdschema.impl.PublicImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ray.bean.CompanyBean;
import com.ray.bean.UserBean;
import com.ray.exception.ServiceException;
import com.ray.pojo.MyUser;
import com.ray.service.CompanyService;
import com.ray.service.PermissionService;
import com.ray.service.UserService;
import com.ray.service.WeiXinService;
import com.ray.util.CookieUtils;
import com.ray.util.MD5FileUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil;
import com.ray.util.redis.RedisCache;

import net.sf.json.JSONObject;


@Controller
@RequestMapping("user")
public class UserController {
	@Autowired
	UserService userService;
	@Autowired
	CompanyService companyService;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	PermissionService permissionService;
	
	
	/**
	 * 关联验证
	 * @param request
	 * @param user
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Map login(HttpServletRequest request,MyUser user) throws ServiceException {
		MyUser myUser=userService.getUser(user);
		user.setUserId(myUser.getUserId());
		user.setCompany(myUser.getCompany());
		Map map=new HashMap();
		map.put("loginCompany", myUser.getCompany());
		CompanyBean cc=companyService.getCompany(map);
		Assert.isTrue(cc.getStatus()!=0,"公司未审核,审核请联系：叶先生-15157767765");
		Assert.isTrue(cc.getStatus()!=2,"公司审核未通过");
		userService.relationWeiXin(user);
		return ResponseUtil.ResponseResult("");
	}
	
	
	/**
	 * 验证码登录
	 * @param request
	 * @param user
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("/loginByVerificationCode")
	@ResponseBody
	public Map loginByVerificationCode(HttpServletRequest request,HttpServletResponse response,MyUser user) throws ServiceException {
		MyUser myUser=userService.getUser(user);
		user.setUserId(myUser.getUserId());
		Map map=new HashMap();
		map.put("loginCompany", myUser.getCompany());
		CompanyBean cc=companyService.getCompany(map);
		Assert.isTrue(cc.getStatus()!=0,"公司未审核,审核请联系：叶先生-15157767765");
		Assert.isTrue(cc.getStatus()!=2,"公司审核未通过");
		if(cc.getIsNeedCode()==1) {
			//如果验证码校验通过 
     		Assert.isTrue(userService.VerificationCode(user),"验证码错误");
		}
		myUser.setPermissionList(permissionService.getUserPermissionBeanByUserId(myUser.getUserId()));
		request.getSession().setAttribute("userLogin", myUser);	
		/**
		 * 实现自动登陆 autoLogin
		 */
		if (request.getParameter("autoLogin")!=null&&"autoLogin".equals(request.getParameter("autoLogin"))) {
			String autoLoginKey="autoLogin_"+MD5FileUtil.getMD5String(new Date().getTime()+myUser.getUserId());
			RedisCache.setDataToRedis(autoLoginKey, myUser, null);
			CookieUtils.setCookie(request, response, "autoLogin", autoLoginKey,60*60*24*365*10);
		}
		return ResponseUtil.ResponseResult("");
	}
	
	
	/**
	 * 发送验证码
	 * @param request
	 * @param user
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("/sendVerificationCode")
	@ResponseBody
	public Map sendVerificationCode(HttpServletRequest request,MyUser user) throws ServiceException {
		MyUser myUser=userService.getUser(user);
		return ResponseUtil.ResponseResult(userService.sendVerificationCode(myUser.getUserId(),request));
	}
	
	
	@RequestMapping("/getManager")
	@ResponseBody
	public Map getManager(String workShop) throws ServiceException {
		UserBean userBean=userService.getManager(workShop);
		return ResponseUtil.ResponseResult(userBean);
	}
	
	
	@RequestMapping("/getUserName")
	@ResponseBody
	public Map getUserName(HttpServletRequest request) throws ServiceException {
		MyUser myuser=RequestUtil.getLoginUser(request);
		return ResponseUtil.ResponseResult(myuser);
	}
	
	@RequestMapping("/jiaoYanPass")
	@ResponseBody
	public Map jiaoYanPass(HttpServletRequest request,String password) throws ServiceException {
		MyUser myuser=RequestUtil.getLoginUser(request);
		myuser.setPassword(password);
		return ResponseUtil.ResponseResult(userService.jiaoYanPass(myuser));
	}
	
	@RequestMapping("/updatePassword")
	@ResponseBody
	public Map updatePassword(HttpServletRequest request,String password) throws ServiceException {
		MyUser myuser=RequestUtil.getLoginUser(request);
		myuser.setPassword(password);
		userService.updatePassword(myuser);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	
	@RequestMapping("/loginOut")
	public String loginOut(HttpServletRequest request,HttpServletResponse response) throws ServiceException {
		request.getSession().setAttribute("userLogin", null);
		return "redirect:../login.html";
	}
	
	@RequestMapping("/logoutSystem")
	public Map logoutSystem(HttpServletRequest request,HttpServletResponse response) throws ServiceException {
		request.getSession().setAttribute("userLogin", null);
		return ResponseUtil.ResponseResult(true);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param loginToken(微信openid)
	 * @param pageType(重定向页面)
	 * @return
	 * @throws ServiceException
	 * @throws IOException 
	 */
	@RequestMapping("/getUserByToken")
	public String getUserByToken(HttpServletRequest request,HttpServletResponse response,String loginToken,String pageType) throws ServiceException, IOException {
	    Map<String,String> map =RequestUtil.getRequestAllParamNotLogin2String(request);
		MyUser myUser=userService.getUserByToken(map,pageType);
		String page="";
		if(myUser==null) {
			page= "redirect:../login.html";
		}else {
			myUser.setPermissionList(permissionService.getUserPermissionBeanByUserId(myUser.getUserId()));
			CompanyBean company = userService.getCompanyInfo(myUser.getCompany());
			myUser.setCompanyInfo(company);
			/*增加软件到期服务时间判断*/
	        if(company.getEndTime() != null) {
	        	 DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		    	try {
					if(df.parse(company.getEndTime()).getTime() < new Date().getTime()) {
						 throw new ServiceException("抱歉,系统服务已到期,请续费");
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
			request.getSession().setAttribute("userLogin", myUser);
			if(pageType.indexOf("autoLogin")>-1) {//存在自动登陆参数则自动登陆
				//需要自动登陆
				String autoLoginKey="autoLogin_"+MD5FileUtil.getMD5String(new Date().getTime()+myUser.getUserId());
				RedisCache.setDataToRedis(autoLoginKey, myUser, null);
				CookieUtils.setCookie(request, response, "autoLogin", autoLoginKey,60*60*24*365*10);
			}
			page="redirect:"+pageType;
		}
		return page;
	}
	
	//上传文件添加人员
	@RequestMapping(value="/addPeopleByFile",method=RequestMethod.POST)
	@ResponseBody
	public Map addPeopleByFile(MultipartFile filename,HttpServletRequest request) throws ServiceException, IOException {
		MyUser myUser=RequestUtil.getLoginUser(request);
		return ResponseUtil.ResponseResult(userService.addPeopleByFile(filename,myUser));
	}
	
	//获取车间用户
	@RequestMapping("/getDeptUser")
	@ResponseBody
	public Map getDeptUser(HttpServletRequest request) throws ServiceException, IOException {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.getDeptUser(map));
	}
	
	
	//获取部门用户
	@RequestMapping("/getDepartmentUser")
	@ResponseBody
	public Map getDepartmentUser(HttpServletRequest request) throws ServiceException, IOException {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.getDepartmentUser(map));
	}
	
	/**
	 * 获取有效的部门用户
	* @date 2018年6月1日 下午1:38:20 
	* @author 李斌
	* @return Map 
	* @throws
	 */
	@RequestMapping("/getDepartmentUserOnValid")
	@ResponseBody 
	public Map getDepartmentUserOnValid(HttpServletRequest request) throws ServiceException, IOException {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.getDeptUserByDeptName(map));
	}
	
	
	//通过用户名或者手机号获取用户信息
	@RequestMapping("/querryUserByNameOrPhone")
	@ResponseBody
	public Map querryUserByNameOrPhone(String nameOrPhone,HttpServletRequest request) throws ServiceException, IOException {
		MyUser myuser=RequestUtil.getLoginUser(request);
		String company=myuser.getCompany();
		return ResponseUtil.ResponseResult(userService.querryUserByNameOrPhone(nameOrPhone,company));
	}
	
	
	//获取所有用户
	@RequestMapping("/queryAllUser")
	@ResponseBody
	public Map queryAllUser(HttpServletRequest request) throws ServiceException, IOException {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.queryAllUser(map));
	}
	
	
	/**
	 * 获取所有部门
	* @date 2018年5月12日 上午9:13:31 
	* @author 李斌
	* @return Map<String,Object> 
	* @throws
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getDepartment") 
	public Map<String,Object> getAllDepartment(HttpServletRequest request) throws ServiceException{
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(userService.getAllDepartment(map));
	}
	
	@RequestMapping("/sh")
	public String  sh(String redirectUrl,HttpServletRequest request) throws UnsupportedEncodingException {
		String url= WeiXinUtil.getWeiXinPubliucNumberCodeUrl(WeiXinParamesUtil.weiXinPublicNumberRedirectUrl+redirectUrl);
		System.out.println(url);
		return "redirect:"+url;
	}
	
	
	@RequestMapping("/weiXinPublicNumberRedirectUrl")
	public String  weiXinPublicNumberRedirectUrl(String redirectUrl,String code,String state,Model model,HttpServletRequest request) throws ServiceException, IOException {
		MyUser myUser=weiXinService.getWeiXinPublicNumberReportUser(code,request,"",redirectUrl);
		if(myUser.getUserName()==null || "".equals(myUser.getUserName())) {
			model.addAttribute("weiXinPublicOpenId", myUser.getWeiXinPublicOpenId());
			model.addAttribute("weiXinPublicunionId",myUser.getUnionId());
			return "redirect:/login.jsp";
		}else {
			return "redirect:"+redirectUrl;
		}
	}
	
	
	/**
	 * 找回密码校验用户
	 * @param companyName(公司名)
	 * @param userName(用户名)
	 * @param type(找回方式)
	 * @return
	 */
	@RequestMapping("/checkUser")
	@ResponseBody
	public Map checkUser(UserBean userBean,int type)   {
		return ResponseUtil.ResponseResult(userService.checkUser(userBean,type));
	}
	
	
	/**
	 * 找回密码校验用户
	 * @param companyName(公司名)
	 * @param userName(用户名)
	 * @param code(验证码)
	 * @param password(新密码)
	 * @return
	 */
	@RequestMapping("/updatePassworByCode")
	@ResponseBody
	public Map checkUser(UserBean userBean,String  code)   {
		userService.updatePassworByCode(userBean,code);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	/**
	 * 获取人员,内含部门与车间id
	* @date 2018年9月5日 上午8:45:59 
	* @author 李斌
	* @return Map<String,Object> 
	* @throws
	 */
	@RequestMapping("/getUserByDeptAndWork") 
	@ResponseBody
	public Map<String,Object> getUserByDeptAndWork(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.getUserByDeptAndWork(map));
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param loginToken(微信openid)
	 * @param pageType(重定向页面)
	 * @return
	 * @throws ServiceException
	 * @throws IOException 
	 */
	@RequestMapping("/getUserLoginByScanQrcode")
	public String getUserLoginByScanQrcode(HttpServletRequest request,HttpServletResponse response,String code,String state) throws ServiceException, IOException {
		if(code!=null ) {
			JSONObject object = WeiXinUtil.getWeixinScanLoginAccessToken(code);
			if(!object.has("unionid")) {//未关注
				return "redirect:../WeChatQrcode.html";
			}
			String unionId = object.getString("unionid");
			Map<String, String> map=new HashMap<String, String>();
			map.put("loginToken", unionId);
			
			String redirectUrl = "/index.html";
			if("datav".equals(state)) {
				redirectUrl = "/datav/index.html?autoLogin=autoLogin";
			}
			MyUser myUser=userService.getUserByToken(map,redirectUrl);
			
			if(myUser==null) {//未绑定
				return "redirect:../WeChatQrcodeConnectAccount.html";
			}
			myUser=userService.getUser(myUser);
			String page="";
			if(myUser==null) {//未绑定
				page= "redirect:../WeChatQrcodeConnectAccount.html";
			}else {
				myUser.setPermissionList(permissionService.getUserPermissionBeanByUserId(myUser.getUserId()));
				request.getSession().setAttribute("userLogin", myUser);
				if("datav".equals(state)) {//看板
					//需要自动登陆
					String autoLoginKey="autoLogin_"+MD5FileUtil.getMD5String(new Date().getTime()+myUser.getUserId());
					RedisCache.setDataToRedis(autoLoginKey, myUser, null);
					CookieUtils.setCookie(request, response, "autoLogin", autoLoginKey,60*60*24*365*10);
					page= "redirect:../datav/index.html?autoLogin=autoLogin";
				}else {
					page="redirect:../index.html";
				}
			}
			return page;
		}else {
			if("datav".equals(state)) {//看板
				return "redirect:../displayView/login.html?autoLogin=autoLogin";
			}
			return "redirect:../login.html";
		}
		
	}
	
	/**
	 * 申请招聘
	 * @param request
	 * @return
	 */
	@RequestMapping("/applyRecruit") 
	@ResponseBody
	public Map<String,Object> applyRecruit(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.applyRecruit(map));
	}
	
	
	/**
	 * 申请招聘
	 * @param request
	 * @return
	 */
	@RequestMapping("/approvalApplyRecruit") 
	@ResponseBody
	public Map<String,Object> approvalApplyRecruit(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.approvalApplyRecruit(map));
	}
	
	/**
	 * 查询申请招聘信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/getApplyRecruit") 
	@ResponseBody
	public Map<String,Object> getApplyRecruit(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.getApplyRecruit(map));
	}
	
	/**
	 * 查询申请招聘信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/getApplyRecruitNoLogin") 
	@ResponseBody
	public Map<String,Object> getApplyRecruitNoLogin(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParamNotLogin(request);
		return ResponseUtil.ResponseResult(userService.getApplyRecruitNoLogin(map));
	}
	
	
	/**
	 * 应聘者扫码添加应聘记录
	 * @return
	 */
	@RequestMapping("/addCandidateByQRCode") 
	@ResponseBody
	public  Map<String, Object> addCandidateByQRCode(HttpServletRequest request){
		Map map = RequestUtil.getRequestAllParamNotLogin(request);
		return ResponseUtil.ResponseResult(userService.addCandidateByQRCode(map));
	}
	
	
	/**
	 * 获取招聘记录
	 * @param request
	 * @return
	 */
	@RequestMapping("/getCandidateRecord") 
	@ResponseBody
	public Map<String,Object> getCandidateRecord(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.getCandidateRecord(map));
	}
	
	
	/**
	 * 审核
	 * @param request
	 * @return
	 */
	@RequestMapping("/approvalCandidate") 
	@ResponseBody
	public Map<String,Object> approvalCandidate(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(userService.approvalCandidate(map));
	}
	
	
}
